/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package gestion;

import java.awt.Color;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import java.awt.event.ItemEvent;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;

import java.util.GregorianCalendar;
import java.util.Vector;
import javax.swing.DefaultCellEditor;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.event.CellEditorListener;
import javax.swing.event.ChangeEvent;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellEditor;
import org.apache.log4j.Logger;
import impresos.DatosToImprimir;
import otros.Fecha;
import impresos.ImpCompra;
import java.awt.Event;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import javax.swing.AbstractAction;
import javax.swing.ActionMap;
import javax.swing.InputMap;
import javax.swing.JComponent;
import javax.swing.KeyStroke;
import otros.Util;
import tablasSql.Articulos;
import tablasSql.Compras;
import tablasSql.ConsultaBD;
import tablasSql.Proveedor;
import tablasSql.Sql;
import tablasSql.Stock;

/**
 *
 * @author FERRETERIA
 */
public class FCompras extends javax.swing.JInternalFrame {
    
    private final static Logger log = Logger.getLogger(FCompras.class);

//---------------------------------------------------------------------------RELOJ    
    public class Reloj implements Runnable { 

        private String dia, mes, año, hora, minutos, segundos; 
        private Calendar calendario = new GregorianCalendar(); 
        Thread hilo; 
        
        public Reloj() { //Constructor 
            hilo = new Thread(this); 
            hilo.start(); 
        } //fin constructor 

        @ Override 
        public void run() { 
            Thread ct = Thread.currentThread(); 
            while (ct == hilo) { 
                try { 
                    actualiza(); 
                    lblTime.setText("<html><center>" + dia + "/" + mes + "/" + año + " " + hora + ":" + minutos + ":" + segundos); 

                    Thread.sleep(100); 
                } catch (InterruptedException ex) { 
                    log.error(ex.getMessage()); 
                } 
            } 
        } 
        
        public void actualiza() { 
            Date fechaHoraActual = new Date(); 
            calendario.setTime(fechaHoraActual); 

            hora = String.valueOf(calendario.get(Calendar.HOUR_OF_DAY)); 
            minutos = calendario.get(Calendar.MINUTE) > 9 ? "" + calendario.get(Calendar.MINUTE) : "0" + calendario.get(Calendar.MINUTE); 
            segundos = calendario.get(Calendar.SECOND) > 9 ? "" + calendario.get(Calendar.SECOND) : "0" + calendario.get(Calendar.SECOND);
            dia = calendario.get(Calendar.DATE) > 9 ? "" + calendario.get(Calendar.DATE) : "0" + calendario.get(Calendar.DATE); 
            mes = calendario.get(Calendar.MONTH)+1 > 9 ? "" + (calendario.get(Calendar.MONTH)+1) : "0" + (calendario.get(Calendar.MONTH)+1); 
            año = calendario.get(Calendar.YEAR) > 9 ? "" + calendario.get(Calendar.YEAR) : "0" + calendario.get(Calendar.YEAR); 
        }        
    }
    
//---------------------------------------------------------------------------RELOJ    

//---------------------------------------------------------------------TABLA LISTENER         
//  Actualizo las variables de los calculos de la lista de articulos
    public class MiCellEditorListener implements CellEditorListener {

        @Override
        public void editingCanceled(ChangeEvent ce) {
            log.debug("no hago naa");
        }
            
        @Override
        public void editingStopped(ChangeEvent e) {
            int fila = tabla.getSelectedRow();
            int columna = tabla.getSelectedColumn();
            
            if ((columna == 0) && !memoriaId.equals(tabla.getValueAt(fila, 0)))
               buscarArticulo(tabla.getValueAt(fila, 0).toString().trim(), fila);
            
            // compruebo si se ha modificado algo de la fila seleccionada
            boolean todo = true;
            for (int i = 2; (i < 5) && todo; i++)
                if ((tabla.getValueAt(fila, i) == null) || 
                        (tabla.getValueAt(fila, i).toString().equals("")))
                     todo = false;   
                    
            if (todo) { 
                boolean hayar = false;     // variable que me determina que se ha cambiado algo 
                float bCantidad = Float.parseFloat(tabla.getValueAt(fila, 2).toString());
                float bPrecio = Float.parseFloat(tabla.getValueAt(fila, 3).toString().replace(",", "."));
                String descuento = tabla.getValueAt(fila, 4).toString().replace(",", ".").replace("%", "");
                //float bDescuento = Float.parseFloat(tabla.getValueAt(fila, 4).toString().replace(",", ".").replace("%", "").trim());
                
                if (cantidad != bCantidad) {
                    cantidad = bCantidad;
                    hayar = true;
                }
                if (precio != bPrecio) {
                    precio = bPrecio;
                    hayar = true;
                }
                if (!descLinea.equals(descuento)) {
                    descLinea = descuento;
                    hayar = true;
                }
                if (hayar) { 
                    if (tabla.getValueAt(fila, 5) != null) { // compruebo si tiene un total anterior para eliminarlo
                        totalVenta -= total;
                        tratarIgic(igic, true); //resto con el total anterior
                    }
                    calcularLinea();
                    tratarIgic(igic, false);    //hayo el igic
                    tabla.setValueAt((Object)total,fila,5);
                    tabla.setValueAt(calcularCosto(),fila,7);
                }
                
                // si cambio el tipo de igic
                String bIgic = (tabla.getValueAt(fila, 6) != null) ? tabla.getValueAt(fila, 6).toString() : "0";
                if (igic.compareTo(bIgic) != 0) {
                    tratarIgic(igic, true);     //resto el igic anterior
                    tratarIgic(bIgic, false);   //hayo el igic 
                    igic = bIgic;
                    tabla.setValueAt(calcularCosto(),fila,7);
                }      
            }
        }
    }
//---------------------------------------------------------------------TABLA LISTENER    

    private class MiTabla extends JTable{
    
        @Override
        public TableCellEditor getCellEditor(int row, int col) {
            final JTextField field = new JTextField(getValueAt(row,col).toString());
            final DefaultCellEditor edit = new DefaultCellEditor(field);
            edit.setClickCountToStart(1);
            field.addFocusListener(new FocusAdapter() {
                                        @Override
                                        public void focusGained(FocusEvent e) {
                                        field.selectAll();//Con esto al solicitar el editor, el texto queda seleccionado
                                        }
                                        @Override
                                        public void focusLost(FocusEvent e) {
                                        field.select(0,0);//De-selecciono el texto al perder el foco.
                                        }
                                        });
            return edit;
        }
    }
    
    
    //private float descLinea = -1;          // descuento producto
    private String descLinea = "";     // descuento producto    
    private float descPie = 0;
    private float sobreCargo = 0;
    private float cantidad = 1;           
    private float precio = 0;           // costo
    private float totalVenta = 0;       // la suma de precio de todos los productos
    private float total = 0;            // precio del producto cantidad * costo - descuento
    private String igic = "";           // me sirve pa saber que fue lo ultimo introducido
    private float suma3 = 0;
    private float suma7 = 0;
    private int filaEdit;               // fila q se editando
    private int columEdit;              // columna q se esta editando
    private boolean guardar = true;     // factura nueva
    private String memoriaId = "";
    private ArrayList<String>aActualizar;
    private ArrayList<String>creados;
    private int redondeo = 4;
    
    public FCompras() {
        init();
        mapeo();
    }
     
    private void mapeo() {
        ActionMap mapaAccion = this.getActionMap();
        InputMap map = this.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
        //Stock
        KeyStroke linea = KeyStroke.getKeyStroke(KeyEvent.VK_F3,0);
        map.put(linea , "linea");
        mapaAccion.put("linea",F3());
        
    } 
   
     public AbstractAction F3(){
        return new AbstractAction() { 
                    public void actionPerformed(ActionEvent e) {
                        int op = JOptionPane.showOptionDialog(jScrollPane1, "Seleccione opcion", "¿Que quiere hacer con el Stock?", 
                                JOptionPane.YES_NO_OPTION,JOptionPane.QUESTION_MESSAGE, null,
                                new Object[] { "Sumar", "Restar" }, 
                                "Sumar"); 
                        if (op != -1)
                            for (int i = 0; i < tabla.getRowCount();i++) {
                                log.info("Modifico el stock de la compra ---------- suma " + op + " (0 suma/ 1 resta)");
                                if (tabla.getValueAt(i, 0) != null) {
                                    String codigo = tabla.getValueAt(i, 0).toString(); //idArticulo
                                    if ((codigo.length() < 7) && (!codigo.equals("0"))) {
                                            float cantidad = -Float.parseFloat(tabla.getValueAt(i, 2).toString());
                                            if (op==1) cantidad = -cantidad;
                                            if (cbTipoTicket.getSelectedIndex() == 2) 
                                                cantidad = -cantidad;        // nota de abono se resta el stock
                                            Stock.menosStock(codigo, cantidad, new Fecha().getFechaSQL()); //añado stock
                                    }
                                }
                            }
                    }
                };
    }
    
    
    private void init() {
        Util.setConfiguracionLog(Util.LOG4_FICH);
        initComponents();
        Reloj r = new Reloj();
        r.run();
        bXML.setVisible(false);
        
        CellEditorListener ChangeNotification = new MiCellEditorListener(); 
        tabla.getDefaultEditor(Integer.class).addCellEditorListener(ChangeNotification);
        tabla.getDefaultEditor(String.class).addCellEditorListener(ChangeNotification);
        tabla.getDefaultEditor(Float.class).addCellEditorListener(ChangeNotification);
                 
        aActualizar = new ArrayList();
        creados = new ArrayList();
        
        resetFTPV();
        
    }
    
    
    private void activarBotones(boolean activar) {
        bGuardar.setEnabled(activar);
    }
    
    private void resetFTPV() {
        lblF3.setVisible(false);
        txtF3.setVisible(false);
        activarBotones(false);
        getProveedor("1");
        initNumTicket(0);
        resetValores();
        totalVenta = 0;
        mostrarPrecio(totalVenta);
        txtComentario.setText("");
        txtNumFac.setText("");
        borrarTabla();
        guardar = true;
        suma3 = 0;
        suma7 = 0;
        recalcularIgic();
        descPie = 0;
        txtDescuentoPie.setText("0%");
        txtSobreCargo.setText("0%");
        sobreCargo = 0;
        txtNumFac.setText("");
        txtFechaFac.setText("");
        txtFechaPago.setText("");
        txtFechaVenc.setText("");
        txtPeriodo.setText("");
        txtCodProve.requestFocus();
        redondeo = 4;
        creados.clear();
        if (cbTipoTicket.getSelectedIndex()==0) 
            activarFechaVenc(true);
        else
            activarFechaVenc(false);
        if (cbTipoPago.getSelectedIndex() == 0)
            activarFechaPago(true);
        else
            activarFechaPago(false);
        mostrarMensajeError(false);
        bCargarFactura.requestFocus();
    }
        
    private void activarFechaPago(boolean valor) {
        txtFechaPago.setEnabled(valor);
    }
    
    private void activarFechaVenc(boolean valor) {
        txtFechaVenc.setEnabled(valor);
        txtPeriodo.setEnabled(valor);
    }
    
    private void borrarTabla () {  
        if (tabla.isEditing()) 
            //tabla.editingStopped(null);  
            tabla.editingCanceled(null);
        int tam = tabla.getRowCount();
        for (int i = 0; i < tam; i++) 
            ((DefaultTableModel)tabla.getModel()).removeRow(0);
        if (tabla.getRowCount() == 0)
            ((DefaultTableModel)tabla.getModel()).addRow(new Object[] {null,null,null,null,null,null});
    }

//---------------------------------------------------------------Tratamiento factura / albaran 
    private void initNumTicket (int id) {
        if (id == 0)
            id = Sql.getMax("id","compras");
        
        cambiarEstadoTicket();
        txtId.setValue(id);
    }
    
    private void cambiarEstadoTicket() {
        Color color = Util.getColorTicket(cbTipoTicket.getSelectedItem().toString());
        txtId.setBackground(color);
        cbTipoPago.setBackground(color);
        cbTipoTicket.setBackground(color);
        lblF3.setBackground(color);
    }
    
    public void cargarNumTicket(String anio, String numTicket, boolean albaran) {
        cbTipoTicket.setSelectedIndex(albaran ? 1:0);
        txtId.setValue(Integer.parseInt(numTicket));
        txtId.setEditable(true);
    }
    
//------------------------------------------------------------------------------------------------
//---------------------------------------------------------------Tratamiento lista de articulos y precio    
     private void resetValores () {
        cantidad = 1;
        descLinea = "";
        precio = 0;
        total = 0;
        igic = "0";
        memoriaId = "";
    }
    
    private void calcularLinea () {
        String [] desc = descLinea.split("\\+");
        for (int i = 0; i < desc.length; i++ ) {
            float des = 0;
            try {
                des = Float.parseFloat(desc[i]);
            } catch (Exception e){;};
            
            if (i==0)
                total = (1 - des/100) * precio * cantidad;
            else
                total = (1 - des/100) * total;
        }
        total = Util.redondeo(total,redondeo);
        totalVenta += total;
        mostrarPrecio((1.0f - (1.0f * descPie))* totalVenta);
    }
    
    private float calcularCosto () {
        if (!igic.isEmpty())
            return Util.redondeo((((1.0f + (sobreCargo/100)) * total) / cantidad) * (1 + Float.parseFloat(igic)/100),redondeo);
        return 0;
    }
    
    private void mostrarPrecio(Object valor) {
        String precio = Util.getFormatPrecio(valor, redondeo);
        txtPrecioDigital.setText(precio);
        txtPrecioFinal.setText(precio);
    }
   
    private void setVarFila(int fila) {
         Object id = tabla.getValueAt(fila, 0);
         memoriaId = (id != null) ? id.toString() : "";
            
         Object cant = tabla.getValueAt(fila, 2);
         Object prec = tabla.getValueAt(fila, 3);
         Object desc = tabla.getValueAt(fila, 4);
         if((cant != null) && (prec != null) && (desc != null) && //(id != null) && !id.toString().isEmpty() &&
             !cant.toString().isEmpty() && !prec.toString().isEmpty() && !desc.toString().isEmpty()) {
            cantidad = Float.parseFloat(cant.toString());
            precio = Float.parseFloat(prec.toString());
            descLinea = desc.toString().replace(",",".").replace("%", "").trim();
            total = Float.parseFloat(tabla.getValueAt(fila, 5).toString());
         }
         
         Object igi = tabla.getValueAt(fila, 6); 
         igic = ((igi != null) && !igi.toString().isEmpty()) ? igi.toString().trim() : "0";
    }
    
    private void setPrecioFinal() {
        double gastos = (sobreCargo/100) *totalVenta;
        double valor = (1 - (descPie))*totalVenta + hallarIgic(1) + hallarIgic(2) + gastos;
        txtPrecioDigital.setText(Util.getFormatPrecio(valor,redondeo));
        txtGastos.setText(Util.getFormatPrecio(gastos, redondeo));
    }
   
    private void recalcularIgic() {
        total = 0;
        tratarIgic("3.0", false);
        tratarIgic("7.0", false);
    }
    
    private void tratarIgic (String valor, boolean restar) {
        double aSumar = restar ? -total : total;
        switch (valor) {
            case "3.0":
                suma3 += aSumar;
                txtImp3.setText(Util.getFormatPrecio((suma3 *(1 - descPie)) *(1+sobreCargo/100),redondeo));
                break;
            case "7.0":
                suma7 += aSumar;
                txtImp7.setText(Util.getFormatPrecio((suma7 * (1 - descPie))*(1+sobreCargo/100), redondeo));
                break;
        }
        double igicTotal = hallarIgic(1) + hallarIgic(2);
        txtTotalIGIC.setText(Util.getFormatPrecio(igicTotal,redondeo));
        setPrecioFinal();
    }
    
    private double hallarIgic (int tipo) {
        double valor = 0;
        switch (tipo) {
            case 1:
                valor = ((suma3 *(1 - descPie)) *(1+sobreCargo/100)) * 0.03;
                txtCuota3.setText(Util.getFormatPrecio(valor,redondeo));
                break;
            case 2:
                valor = ((suma7 *(1 - descPie)) *(1+sobreCargo/100)) * 0.07;
                txtCuota7.setText(Util.getFormatPrecio(valor,redondeo));
                break;
        }
        return valor; 
    }
    
//------------------------------------------------------------------------------------------------  
//-------------------------------------------------------------Tratamiento de la ventana de error
    private void mostrarMensajeError (int tipo) {
        switch (tipo){
           case 1:
                lblError.setText("<html><P ALIGN=center> ¡¡¡¡Error!!!! <br>Fecha Pago</P>");         
                break;
           case 2:
                lblError.setText("<html><p align=center> ¡¡¡¡Error!!!!<br>F.Vencimiento</p>");
               break;
           case 3:
                lblError.setText("<html><p align=center> ¡¡¡¡Error!!!!<br> Nº de pagos</p>");
               break;
           case 4:
                lblError.setText("<html><p align=center> ¡¡¡¡Error!!!!<br> Nº de pagos</p>");
               break;
           case 5:
                lblError.setText("<html><p align=center> ¡¡¡¡Error!!!!<br>F.Compra</p>");
               break;
        }
        mostrarMensajeError(true);
    }
    
    private void mostrarMensajeError (boolean visible) {
        lblError.setVisible(visible);
        tabla.setVisible(!visible);
    }
//------------------------------------------------------------------------------------------------
//---------------------------------------------------------------------ARTICULOS  
    public void abrirBusquedaArticulo(String aBuscar) {
        FListArticulos la = new FListArticulos(this, Util.FCOMPRAS, aBuscar);
        this.getParent().add(la);
        Principal.centrarFrame(la);
        la.show();
    }

     public void setIdArticuloFromFList(String id, boolean enter) {
        try {
            if (!id.isEmpty()) {
                if (tabla.isEditing())
                    tabla.editingCanceled(null);
                tabla.setValueAt(id, filaEdit, columEdit);
                ResultSet art = Articulos.getArticulo("codigo", id); 
                art.next();
                tabla.setValueAt(art.getString("detalle"), filaEdit, 1);
                tabla.setValueAt(Stock.getStock(id), filaEdit, 2);
                tabla.setValueAt(art.getFloat("costo"), filaEdit, 3);
                if (!memoriaId.equals(id)) {
                    aActualizar.add(id);
                    if (!memoriaId.isEmpty())
                        aActualizar.remove(memoriaId);
                    memoriaId = id;
                }
                tabla.requestFocus();
                
                columEdit = enter ? 1 : 2;  // debido a que si selecciono el objeto con enter o con raton
                tabla.changeSelection(filaEdit, columEdit, false, false);
                tabla.editCellAt(filaEdit, columEdit);
            }
            else
                buscarArticulo("0", filaEdit);
        } catch (SQLException ex) {
            log.warn("setIdArticuloFromFList " + ex);
        }
    }
     
// Determina que es lo que introduzco y busca el articulo para añadirlo a la lista
    public void buscarArticulo(String id, int row) {      
        try {
            String criterio = "codigo";
            ResultSet art = null; 
            if (id.length() > 6) {
                criterio = "codigoBarras1";
                art = Articulos.getArticulo(criterio, id);
                if (!art.next()) 
                    criterio = "codigoBarras2";
            }
            art = Articulos.getArticulo(criterio, id);
            if (art.next()) {
                String codigo = art.getString("codigo"); 
                tabla.setValueAt(codigo, row, 0);
                if (!memoriaId.equals(codigo)) {
                    aActualizar.add(codigo);
                    if (!memoriaId.isEmpty())
                        aActualizar.remove(memoriaId);
                    memoriaId = codigo;
                    tabla.setValueAt(art.getString("detalle"), row, 1);
                    tabla.setValueAt(Stock.getStock(codigo), row, 2);
                    tabla.setValueAt(art.getFloat("costo"), row, 3);
                    columEdit = 1;   
                }
            }
            else {
                int op = JOptionPane.showOptionDialog(this, "Seleccione opcion", "¿Que quiere hacer?", 
                            JOptionPane.YES_NO_CANCEL_OPTION,JOptionPane.QUESTION_MESSAGE, null,
                            new Object[] { "Buscar", "Crear", "No Registrar" }, 
                            "Buscar"); 
                switch (op){
                    case 0:         //bucarlo
                        abrirBusquedaArticulo(null);
                        break;
                    case 1:         //crearlo
                        String clave = Articulos.asignarId(tabla.getValueAt(row, 0).toString());
                        creados.add(clave);
                        aActualizar.add(clave);
                        String datos [] = {clave, new Fecha().getFechaSQL(), "0"};
                        Stock.guardar(datos);
                        tabla.setValueAt(clave, row, 0);
                        columEdit = 1;
                        tabla.editCellAt(filaEdit, columEdit);
                        tabla.changeSelection(filaEdit, columEdit, false, false);
                        break;
                    case 2:         // no guardarlo
                }
            }
        } catch (SQLException ex) {
                //mostrarMensajeError(true,1);
        }
        return;
    }
    
//------------------------------------------------------------------------------
//-------------------------------------------------------------------------CLIENTE    
    public void getProveedor(String pro) {
        try {
            ResultSet res = Proveedor.getProveedor(pro);
            if (res.next()){
                txtCodProve.setText(pro);
                txtNomComercial.setText(res.getString("nombrecomercial"));
                int valor = res.getInt("tipoPago");
                cbTipoTicket.setSelectedIndex(valor / 2);
                cbTipoPago.setSelectedIndex(valor % 2);  
            }
        } catch (SQLException ex) {
            log.warn(ex);
        }
    }
    
    // guardo el ticket en la ficha dl proveedor
    private void guardarTicketProve() {
        String [] dato = {txtId.getText(), txtCodProve.getText()};
        Proveedor.guardarUltTicket(dato, cbTipoTicket.getSelectedIndex());
    }

//------------------------------------------------------------------------------
    public void guardar() {
        ConsultaBD.cursorEspera(this);
         if (tabla.isEditing())
             tabla.editingCanceled(null);
               
        int id = -1; 
        String fechaPago = txtFechaPago.isEnabled() ? new Fecha(txtFechaPago.getText()).getFechaSQL() : null;
        String fechaVen = txtFechaVenc.isEnabled() ? new Fecha(txtFechaVenc.getText()).getFechaSQL() : null;
        String periodo = txtPeriodo.getText();
        
        if (guardar) {
            String datos [] = { new Fecha().getFechaSQL()+ " " + lblTime.getText().substring(24),
                           new Fecha(txtFechaFac.getText()).getFechaSQL() + " " + lblTime.getText().substring(24),
                           fechaPago,
                           fechaVen,
                           txtComentario.getText(),
                           txtNumFac.getText(),
                           txtPrecioDigital.getText().replace("€", "").replace(",",".").trim(),
                           txtSobreCargo.getText().replace("%", "").replace(",",".").trim(),
                           txtDescuentoPie.getText().replace("%", "").replace(",",".").trim(), 
                           txtCodProve.getText(),
                           ""+cbTipoTicket.getSelectedIndex(),
                           ""+cbTipoPago.getSelectedIndex(),
                           (periodo.isEmpty()|| (periodo==null))? "1" : periodo
                           };        
            id = Compras.guardar(datos, guardar);
            txtId.setText(""+id);
        } else {
             String datos [] = { new Fecha().getFechaSQL()+ " " + lblTime.getText().substring(24),
                           new Fecha(txtFechaFac.getText()).getFechaSQL() + " " + lblTime.getText().substring(24), 
                           fechaPago,
                           new Fecha(txtFechaVenc.getText()).getFechaSQL(),
                           txtComentario.getText(),
                           txtNumFac.getText(),
                           txtPrecioDigital.getText().replace("€", "").replace(",",".").trim(),
                           txtSobreCargo.getText().replace("%", "").replace(",",".").trim(),
                           txtDescuentoPie.getText().replace("%", "").trim(), 
                           txtCodProve.getText(),
                           ""+cbTipoTicket.getSelectedIndex(),
                           ""+cbTipoPago.getSelectedIndex(),
                           ""+txtPeriodo.getText(),
                           txtId.getText()
                           };        
            id = Compras.guardar(datos, guardar);       
        }
        log.info("compras.guardar:----------------------------------------------" + id);
        if (id==-1) return;    
        // cuando cargo borro la lista de articulos
        if (!guardar) 
            Compras.borrarListArticulos(Integer.valueOf(txtId.getText()));
        
        int pos = 0;
        int tam = tabla.getRowCount();
        if (tabla.getValueAt(tam-1, 7) == null) tam -=1;
        for (int i = 0; i < tam; i++) {
            String codigo = null;
            log.info("compras.guardar nuevo: " + guardar);
            if ((tabla.getValueAt(i, 0) != null) && !tabla.getValueAt(i, 0).toString().isEmpty()) {
               codigo = tabla.getValueAt(i, 0).toString(); //idArticulo
               log.info("compras.guardar 'stock': " +  codigo + " \tcant: " + tabla.getValueAt(i, 2).toString());
            
               if ((codigo.length() < 7) && (!codigo.equals("0"))) {
                   log.info("modifico el stock");
                   float cantidad = -Float.parseFloat(tabla.getValueAt(i, 2).toString());
                   if (cbTipoTicket.getSelectedIndex() == 2) 
                       cantidad = -cantidad; // nota de abono se resta el stock
                   else                      // actualizo los datos del articulo cuando no es nota de abono   
                       actualizarArticulo(i);
                   Stock.menosStock(codigo, cantidad, new Fecha().getFechaSQL()); //añado stock
                   
               }
            }                 
            String datos2 [] = {tabla.getValueAt(i, 1).toString(), //detalle
                             tabla.getValueAt(i, 4).toString().replace("%", "").trim(), //descuento
                             tabla.getValueAt(i, 3).toString().replace(",",".").trim(), //precio
                             tabla.getValueAt(i, 5).toString().replace(",",".").trim(), //total
                             tabla.getValueAt(i, 7).toString().replace(",",".").trim(), //costo
                             tabla.getValueAt(i, 2).toString().replace(",",".").trim(), //cantidad
                             tabla.getValueAt(i, 6).toString().replace(",",".").trim(), //IGIC
                             codigo,
                             ""+pos++,
                             txtId.getText()
                           };
            Compras.guardarLista(datos2);
        }
        guardarTicketProve();
        ConsultaBD.cursorNormal(this);
    }
    
    private void abrirNuevosArticulos () {
        JOptionPane.showMessageDialog(this, "Actualice " + aActualizar.size() + " articulos.");
        for (int i = 0; i < aActualizar.size(); i++) {
            abrirArticulo(aActualizar.get(i));
        }
        aActualizar.clear();
    }
    
    private void abrirArticulo(String id) {
        FArticulo a = new FArticulo(id);
        this.getParent().add(a);        
        Principal.centrarFrame(a);
        a.show();
    }
    
    private void abrirStock(String codigo) {
        FStock s = new FStock (codigo);
        if (s.hasArticulo()) {
            Principal.panel.add (s);
            s.show();
            s.txtStock.requestFocus();
            s.txtStock.selectAll();
        }
    }
     
    private void actualizarArticulo (int i) {
        String datos [] = {tabla.getValueAt(i, 1).toString(),                   // detalle    
                           tabla.getValueAt(i, 7).toString().replace(",",".").trim(),  // costo
                           tabla.getValueAt(i, 6).toString().replace(",",".").replace("%","").trim(), //igic
                           tabla.getValueAt(i, 0).toString()                    // id
                          };
        Articulos.actualizarArtCompra(datos);
    }
    
    public void cargar (int id) {
        initNumTicket(id);
        cargar();
    }
                
    public void cargar () {
        ConsultaBD.cursorEspera(this);
        borrarTabla();
        lblF3.setVisible(true);
        txtF3.setVisible(true);
        ResultSet datos = Compras.getCompra(Integer.valueOf(txtId.getText()));
        try{
            //------------------------------------------------------------datos de Factura
            datos.next();
            getProveedor(String.valueOf(datos.getInt("idprove")));
            descPie = datos.getFloat("descuento");
            txtDescuentoPie.setText(""+descPie + "%");
            descPie /= 100;
            sobreCargo = datos.getFloat("sobreCargo");
            txtSobreCargo.setText(""+sobreCargo);
            float totalFact = datos.getFloat("total");
            mostrarPrecio(totalFact); 
            txtComentario.setText(datos.getString("observacion"));
            cbTipoTicket.setSelectedIndex(datos.getInt("tipo"));
            cbTipoPago.setSelectedIndex(datos.getInt("tipopago"));
            txtNumFac.setText(""+datos.getString("numFact"));
            if (datos.getString("fechaCom") != null) {
                String fecha [] = datos.getString("fechaCom").substring(0,11).trim().split("-");
                txtFechaFac.setText(fecha[2] + "/" + fecha[1] + "/" + fecha[0]);
            }
            if (datos.getString("fechaPago") != null) {
                String fecha [] = datos.getString("fechaPago").substring(0,11).trim().split("-");
                txtFechaPago.setText(fecha[2] + "/" + fecha[1] + "/" + fecha[0]);
            }
            if (datos.getString("fechaVenc") != null) {
                String fecha [] = datos.getString("fechaVenc").substring(0,11).trim().split("-");
                txtFechaVenc.setText(fecha[2] + "/" + fecha[1] + "/" + fecha[0]);
            }
            txtPeriodo.setText(""+datos.getInt("periodo"));
            //--------------------------------------------------------------Lista de articulos
            datos = Compras.getListArticulos(Integer.valueOf(txtId.getText()));           
            while (datos.next()) {
                String codigo = ""+datos.getInt("idarticulo");
                if (codigo.length() < 7) {
                    if (Articulos.is(Integer.parseInt(codigo))) {
                       float cantidad = datos.getFloat("cantidad");
                       if (cbTipoTicket.getSelectedIndex()==2) cantidad = -cantidad; //nota de abono sumo stock
                       Stock.menosStock(codigo, cantidad); // Restauro stock
                    }
                    else
                        codigo = "0";
                }
                tabla.setValueAt(codigo, tabla.getRowCount()-1, 0);    
                tabla.setValueAt(datos.getString("detalle"), tabla.getRowCount()-1, 1);
                tabla.setValueAt(datos.getFloat("cantidad"), tabla.getRowCount()-1, 2);
                tabla.setValueAt(datos.getFloat("precio"), tabla.getRowCount()-1, 3);
                tabla.setValueAt(datos.getString("descuento"), tabla.getRowCount()-1, 4);
                total = datos.getFloat("total");
                totalVenta += total;
                tabla.setValueAt(total, tabla.getRowCount()-1, 5);
                igic = "" + datos.getFloat("tipoIgic");
                tabla.setValueAt(datos.getFloat("tipoIgic"), tabla.getRowCount()-1, 6);
                tratarIgic(igic, false);
                tabla.setValueAt(Util.redondeo(datos.getFloat("costo"),redondeo), tabla.getRowCount()-1, 7);
                ((DefaultTableModel)tabla.getModel()).addRow(new Object[] {null,null,null,null,null,null});
            }        
            tabla.scrollRectToVisible(tabla.getCellRect(tabla.getRowCount()-1, 0, true));
            //---------------------------------------------------------------
            txtPrecioFinal.setText(Util.getFormatPrecio(totalVenta, redondeo));
            txtGastos.setText(Util.getFormatPrecio(totalVenta*sobreCargo/100, redondeo));
            guardar = false;
            cambiarEstadoTicket();
            SePuedeGrabar();
        } catch (SQLException ex) {
            log.warn("cargar: " +ex);
        }
        ConsultaBD.cursorNormal(this);
    }
    
    
    private void SePuedeGrabar() {
        if (!txtNumFac.getText().isEmpty() && !txtFechaFac.getText().isEmpty() && !txtSobreCargo.getText().isEmpty() )
            activarBotones(true);
        else
            activarBotones(false);
    }
    
    private boolean comprobarCampos() {
        if (txtFechaPago.isEnabled()) {
            if(!Fecha.formatoCorrecto(txtFechaPago.getText())) {
                mostrarMensajeError(1);
                return false;
            }
        }
        if (txtFechaVenc.isEnabled()) {
            if(!Fecha.formatoCorrecto(txtFechaVenc.getText())) {
                mostrarMensajeError(2);
                return false;
            }
            if (txtPeriodo.getText().isEmpty() || txtPeriodo.getText() == null) {
                mostrarMensajeError(3);
                return false;
            }
            else {
                try {
                    DecimalFormat df = new DecimalFormat("00");
                    df.format(Integer.parseInt(""+txtPeriodo.getText()));
                }
                catch (Exception e) {
                    mostrarMensajeError(4);
                    return false;
                }
            }
        }
        return true;
    }
    
    private String fechaPagoCoarco() {
        String dia = "";
        String aux [] = txtFechaFac.getText().split("/");
        int mes = ((Integer.parseInt(aux[1])+1) % 12);
        if (mes == 0) mes = 12;
        int año = Integer.parseInt(aux[2]);
        if (mes == 1) año++;
        switch(aux[0]) {
            case "01":
            case "02":
            case "03":
            case "04":
            case "05":
            case "06":
            case "07":
            case "08":
            case "09":
            case "10":
                dia += "10";
                break;
            case "11":
            case "12":
            case "13":
            case "14":
            case "15":
            case "16":
            case "17":
            case "18":
            case "19":
            case "20":
                dia += "20";
                break;
            default:
                switch (mes) {
                    case 1:
                    case 3:
                    case 5:
                    case 7:
                    case 8:
                    case 10:
                    case 12:
                        dia += "31";
                        break;
                    case 4:
                    case 6:
                    case 9:
                    case 11:
                        dia = "30";
                    default: 
                        if (((año % 4) == 0) && ((año % 100) != 100 ) 
                            || ((año % 400 ) == 0)) 
                            dia = "29";
                        else
                            dia = "28";
                        break;   
                }
       
                break;
        }
        DecimalFormat df = new DecimalFormat("00");
        return dia + "/" + df.format(mes) + "/" + año;
    }
    
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        java.awt.GridBagConstraints gridBagConstraints;

        pTipoTicket = new javax.swing.JPanel();
        cbTipoTicket = new javax.swing.JComboBox();
        txtId = new javax.swing.JFormattedTextField();
        bCargarFactura = new javax.swing.JButton();
        cbTipoPago = new javax.swing.JComboBox();
        pCliente = new javax.swing.JPanel();
        txtCodProve = new javax.swing.JTextField();
        txtNomComercial = new javax.swing.JTextField();
        pReloj = new javax.swing.JPanel();
        lblTime = new javax.swing.JLabel();
        txtPrecioDigital = new javax.swing.JTextField();
        pProductos = new javax.swing.JPanel();
        jLabel4 = new javax.swing.JLabel();
        txtNumFac = new javax.swing.JTextField();
        jLabel5 = new javax.swing.JLabel();
        txtFechaFac = new javax.swing.JTextField();
        bXML = new javax.swing.JButton();
        txtFechaPago = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        txtFechaVenc = new javax.swing.JTextField();
        jLabel7 = new javax.swing.JLabel();
        txtPeriodo = new javax.swing.JTextField();
        jLabel8 = new javax.swing.JLabel();
        txtF3 = new javax.swing.JLabel();
        lblF3 = new javax.swing.JTextField();
        pIgic = new javax.swing.JPanel();
        jLabel13 = new javax.swing.JLabel();
        txtImp3 = new javax.swing.JTextField();
        jLabel15 = new javax.swing.JLabel();
        txt3 = new javax.swing.JTextField();
        txtImp7 = new javax.swing.JTextField();
        txt7 = new javax.swing.JTextField();
        jLabel19 = new javax.swing.JLabel();
        txtCuota3 = new javax.swing.JTextField();
        txtCuota7 = new javax.swing.JTextField();
        pBotones = new javax.swing.JPanel();
        bGuardar = new javax.swing.JButton();
        bBorrar = new javax.swing.JButton();
        pFinal = new javax.swing.JPanel();
        jLabel16 = new javax.swing.JLabel();
        txtComentario = new javax.swing.JTextField();
        pPrecio = new javax.swing.JPanel();
        jLabel14 = new javax.swing.JLabel();
        txtDescuentoPie = new javax.swing.JTextField();
        jLabel17 = new javax.swing.JLabel();
        txtPrecioFinal = new javax.swing.JTextField();
        jLabel18 = new javax.swing.JLabel();
        txtTotalIGIC = new javax.swing.JTextField();
        jLabel20 = new javax.swing.JLabel();
        txtGastos = new javax.swing.JTextField();
        txtSobreCargo = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        lblError = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        tabla = new javax.swing.JTable();

        setClosable(true);
        setTitle("Compras");
        setFrameIcon(new javax.swing.ImageIcon(getClass().getResource("/img/icono2.png"))); // NOI18N
        addInternalFrameListener(new javax.swing.event.InternalFrameListener() {
            public void internalFrameActivated(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameClosed(javax.swing.event.InternalFrameEvent evt) {
                formInternalFrameClosed(evt);
            }
            public void internalFrameClosing(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameDeactivated(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameDeiconified(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameIconified(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameOpened(javax.swing.event.InternalFrameEvent evt) {
            }
        });
        getContentPane().setLayout(new java.awt.GridBagLayout());

        pTipoTicket.setMinimumSize(new java.awt.Dimension(380, 40));
        pTipoTicket.setPreferredSize(new java.awt.Dimension(380, 40));
        pTipoTicket.setLayout(new java.awt.GridBagLayout());

        cbTipoTicket.setMaximumRowCount(3);
        cbTipoTicket.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Factura", "Albaran", "Abono" }));
        cbTipoTicket.setMinimumSize(new java.awt.Dimension(82, 20));
        cbTipoTicket.setPreferredSize(new java.awt.Dimension(82, 20));
        cbTipoTicket.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                cbTipoTicketItemStateChanged(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
        pTipoTicket.add(cbTipoTicket, gridBagConstraints);

        txtId.setEditable(false);
        txtId.setBackground(new java.awt.Color(255, 102, 0));
        txtId.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.NumberFormatter(new java.text.DecimalFormat("00000000000000000000"))));
        txtId.setHorizontalAlignment(javax.swing.JTextField.CENTER);
        txtId.setText("01234567890123456789");
        txtId.setToolTipText("");
        txtId.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
        txtId.setMinimumSize(new java.awt.Dimension(215, 28));
        txtId.setPreferredSize(new java.awt.Dimension(215, 28));
        txtId.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                txtIdMouseClicked(evt);
            }
        });
        txtId.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                txtIdKeyReleased(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridheight = 2;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
        gridBagConstraints.insets = new java.awt.Insets(0, 5, 0, 5);
        pTipoTicket.add(txtId, gridBagConstraints);

        bCargarFactura.setText("Cargar");
        bCargarFactura.setPreferredSize(new java.awt.Dimension(66, 28));
        bCargarFactura.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bCargarFacturaActionPerformed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridheight = 2;
        pTipoTicket.add(bCargarFactura, gridBagConstraints);

        cbTipoPago.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Contado", "Credito" }));
        cbTipoPago.setMinimumSize(new java.awt.Dimension(82, 20));
        cbTipoPago.setPreferredSize(new java.awt.Dimension(82, 20));
        cbTipoPago.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                cbTipoPagoItemStateChanged(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 1;
        pTipoTicket.add(cbTipoPago, gridBagConstraints);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
        gridBagConstraints.insets = new java.awt.Insets(15, 20, 3, 0);
        getContentPane().add(pTipoTicket, gridBagConstraints);

        pCliente.setMinimumSize(new java.awt.Dimension(380, 40));
        pCliente.setPreferredSize(new java.awt.Dimension(380, 40));
        pCliente.setLayout(new java.awt.GridBagLayout());

        txtCodProve.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        txtCodProve.setHorizontalAlignment(javax.swing.JTextField.CENTER);
        txtCodProve.setText("0");
        txtCodProve.setToolTipText("f2: abre la busqueda de proveedores");
        txtCodProve.setMinimumSize(new java.awt.Dimension(35, 30));
        txtCodProve.setPreferredSize(new java.awt.Dimension(35, 30));
        txtCodProve.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                txtCodProveMouseClicked(evt);
            }
        });
        txtCodProve.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                txtCodProveKeyPressed(evt);
            }
            public void keyReleased(java.awt.event.KeyEvent evt) {
                txtCodProveKeyReleased(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
        gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 3);
        pCliente.add(txtCodProve, gridBagConstraints);

        txtNomComercial.setEditable(false);
        txtNomComercial.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        txtNomComercial.setText("Ventas Contado");
        txtNomComercial.setMinimumSize(new java.awt.Dimension(35, 30));
        txtNomComercial.setPreferredSize(new java.awt.Dimension(59, 30));
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 2;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.ipadx = 300;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
        pCliente.add(txtNomComercial, gridBagConstraints);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.insets = new java.awt.Insets(0, 20, 0, 0);
        getContentPane().add(pCliente, gridBagConstraints);

        pReloj.setPreferredSize(new java.awt.Dimension(300, 158));
        pReloj.setLayout(new java.awt.GridBagLayout());

        lblTime.setBackground(new java.awt.Color(0, 0, 0));
        lblTime.setFont(new java.awt.Font("Raavi", 0, 18)); // NOI18N
        lblTime.setForeground(new java.awt.Color(255, 255, 255));
        lblTime.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        lblTime.setText("19/11/2013   09:38:00");
        lblTime.setAlignmentY(0.0F);
        lblTime.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED, null, new java.awt.Color(153, 153, 153), null, new java.awt.Color(51, 51, 51)));
        lblTime.setMaximumSize(new java.awt.Dimension(300, 37));
        lblTime.setMinimumSize(new java.awt.Dimension(300, 30));
        lblTime.setOpaque(true);
        lblTime.setPreferredSize(new java.awt.Dimension(100, 30));
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
        gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
        pReloj.add(lblTime, gridBagConstraints);

        txtPrecioDigital.setEditable(false);
        txtPrecioDigital.setBackground(new java.awt.Color(255, 255, 255));
        txtPrecioDigital.setFont(new java.awt.Font("MS UI Gothic", 1, 40)); // NOI18N
        txtPrecioDigital.setHorizontalAlignment(javax.swing.JTextField.CENTER);
        txtPrecioDigital.setText("0,0000€");
        txtPrecioDigital.setFocusable(false);
        txtPrecioDigital.setMaximumSize(new java.awt.Dimension(300, 60));
        txtPrecioDigital.setMinimumSize(new java.awt.Dimension(300, 60));
        txtPrecioDigital.setPreferredSize(new java.awt.Dimension(300, 60));
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.ipady = 40;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
        pReloj.add(txtPrecioDigital, gridBagConstraints);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.gridheight = 3;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.insets = new java.awt.Insets(10, 6, 0, 20);
        getContentPane().add(pReloj, gridBagConstraints);

        pProductos.setMaximumSize(new java.awt.Dimension(380, 71));
        pProductos.setMinimumSize(new java.awt.Dimension(380, 69));
        pProductos.setPreferredSize(new java.awt.Dimension(380, 71));
        pProductos.setLayout(new java.awt.GridBagLayout());

        jLabel4.setText("Nº:");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST;
        gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 5);
        pProductos.add(jLabel4, gridBagConstraints);

        txtNumFac.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        txtNumFac.setHorizontalAlignment(javax.swing.JTextField.CENTER);
        txtNumFac.setMinimumSize(new java.awt.Dimension(150, 23));
        txtNumFac.setPreferredSize(new java.awt.Dimension(172, 23));
        txtNumFac.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                txtNumFacMouseClicked(evt);
            }
        });
        txtNumFac.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                txtNumFacKeyReleased(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.gridwidth = 3;
        pProductos.add(txtNumFac, gridBagConstraints);

        jLabel5.setText("Fecha:");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 2;
        gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 5);
        pProductos.add(jLabel5, gridBagConstraints);

        txtFechaFac.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        txtFechaFac.setHorizontalAlignment(javax.swing.JTextField.CENTER);
        txtFechaFac.setToolTipText("dd/mm/yyyy");
        txtFechaFac.setMinimumSize(new java.awt.Dimension(150, 23));
        txtFechaFac.setPreferredSize(new java.awt.Dimension(85, 23));
        txtFechaFac.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                txtFechaFacMouseClicked(evt);
            }
        });
        txtFechaFac.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                txtFechaFacKeyReleased(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 2;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
        pProductos.add(txtFechaFac, gridBagConstraints);

        bXML.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/xml.png"))); // NOI18N
        bXML.setMaximumSize(new java.awt.Dimension(71, 71));
        bXML.setMinimumSize(new java.awt.Dimension(10, 10));
        bXML.setPreferredSize(new java.awt.Dimension(10, 10));
        bXML.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bXMLActionPerformed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 1;
        pProductos.add(bXML, gridBagConstraints);

        txtFechaPago.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        txtFechaPago.setHorizontalAlignment(javax.swing.JTextField.CENTER);
        txtFechaPago.setToolTipText("dd/mm/yyyy");
        txtFechaPago.setMinimumSize(new java.awt.Dimension(150, 23));
        txtFechaPago.setPreferredSize(new java.awt.Dimension(85, 23));
        txtFechaPago.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                txtFechaPagoMouseClicked(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 4;
        gridBagConstraints.gridy = 2;
        gridBagConstraints.insets = new java.awt.Insets(0, 2, 0, 0);
        pProductos.add(txtFechaPago, gridBagConstraints);

        jLabel3.setText("Compra");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 1;
        pProductos.add(jLabel3, gridBagConstraints);

        jLabel6.setText("Pagado");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 4;
        gridBagConstraints.gridy = 1;
        pProductos.add(jLabel6, gridBagConstraints);

        txtFechaVenc.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        txtFechaVenc.setHorizontalAlignment(javax.swing.JTextField.CENTER);
        txtFechaVenc.setToolTipText("dd/mm/yyyy");
        txtFechaVenc.setMinimumSize(new java.awt.Dimension(150, 23));
        txtFechaVenc.setPreferredSize(new java.awt.Dimension(85, 23));
        txtFechaVenc.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                txtFechaVencMouseClicked(evt);
            }
        });
        txtFechaVenc.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                txtFechaVencKeyReleased(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 2;
        gridBagConstraints.gridy = 2;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST;
        gridBagConstraints.insets = new java.awt.Insets(0, 2, 0, 0);
        pProductos.add(txtFechaVenc, gridBagConstraints);

        jLabel7.setText("Vencimiento");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 2;
        gridBagConstraints.gridy = 1;
        pProductos.add(jLabel7, gridBagConstraints);

        txtPeriodo.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        txtPeriodo.setHorizontalAlignment(javax.swing.JTextField.CENTER);
        txtPeriodo.setToolTipText("");
        txtPeriodo.setMinimumSize(new java.awt.Dimension(45, 23));
        txtPeriodo.setPreferredSize(new java.awt.Dimension(45, 23));
        txtPeriodo.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                txtPeriodoMouseClicked(evt);
            }
        });
        txtPeriodo.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                txtPeriodoKeyReleased(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 3;
        gridBagConstraints.gridy = 2;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST;
        gridBagConstraints.insets = new java.awt.Insets(0, 2, 0, 0);
        pProductos.add(txtPeriodo, gridBagConstraints);

        jLabel8.setText("Nº pagos");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 3;
        gridBagConstraints.gridy = 1;
        pProductos.add(jLabel8, gridBagConstraints);

        txtF3.setText("Stock");
        pProductos.add(txtF3, new java.awt.GridBagConstraints());

        lblF3.setEditable(false);
        lblF3.setBackground(new java.awt.Color(255, 255, 51));
        lblF3.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        lblF3.setHorizontalAlignment(javax.swing.JTextField.CENTER);
        lblF3.setText("F3");
        lblF3.setPreferredSize(new java.awt.Dimension(20, 20));
        lblF3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                lblF3ActionPerformed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 4;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
        pProductos.add(lblF3, gridBagConstraints);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 2;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.SOUTH;
        gridBagConstraints.insets = new java.awt.Insets(0, 20, 0, 0);
        getContentPane().add(pProductos, gridBagConstraints);

        pIgic.setMinimumSize(new java.awt.Dimension(240, 60));
        pIgic.setOpaque(false);
        pIgic.setPreferredSize(new java.awt.Dimension(240, 60));
        pIgic.setLayout(new java.awt.GridBagLayout());

        jLabel13.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel13.setText("Importe");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        pIgic.add(jLabel13, gridBagConstraints);

        txtImp3.setEditable(false);
        txtImp3.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        txtImp3.setHorizontalAlignment(javax.swing.JTextField.CENTER);
        txtImp3.setText("0,0000€");
        txtImp3.setBorder(null);
        txtImp3.setMinimumSize(new java.awt.Dimension(110, 20));
        txtImp3.setPreferredSize(new java.awt.Dimension(110, 20));
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridy = 1;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST;
        pIgic.add(txtImp3, gridBagConstraints);

        jLabel15.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel15.setText("IGIC %");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        pIgic.add(jLabel15, gridBagConstraints);

        txt3.setEditable(false);
        txt3.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        txt3.setHorizontalAlignment(javax.swing.JTextField.CENTER);
        txt3.setText("3%");
        txt3.setBorder(null);
        txt3.setMinimumSize(new java.awt.Dimension(30, 20));
        txt3.setPreferredSize(new java.awt.Dimension(30, 20));
        txt3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txt3ActionPerformed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 1;
        pIgic.add(txt3, gridBagConstraints);

        txtImp7.setEditable(false);
        txtImp7.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        txtImp7.setHorizontalAlignment(javax.swing.JTextField.CENTER);
        txtImp7.setText("0,0000€");
        txtImp7.setBorder(null);
        txtImp7.setMinimumSize(new java.awt.Dimension(110, 20));
        txtImp7.setPreferredSize(new java.awt.Dimension(110, 20));
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridy = 2;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST;
        pIgic.add(txtImp7, gridBagConstraints);

        txt7.setEditable(false);
        txt7.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        txt7.setHorizontalAlignment(javax.swing.JTextField.CENTER);
        txt7.setText("7%");
        txt7.setBorder(null);
        txt7.setMinimumSize(new java.awt.Dimension(30, 20));
        txt7.setPreferredSize(new java.awt.Dimension(30, 20));
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 2;
        pIgic.add(txt7, gridBagConstraints);

        jLabel19.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel19.setText("Cuota");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 2;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        pIgic.add(jLabel19, gridBagConstraints);

        txtCuota3.setEditable(false);
        txtCuota3.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        txtCuota3.setHorizontalAlignment(javax.swing.JTextField.CENTER);
        txtCuota3.setText("0,0000€");
        txtCuota3.setBorder(null);
        txtCuota3.setMinimumSize(new java.awt.Dimension(110, 20));
        txtCuota3.setPreferredSize(new java.awt.Dimension(110, 20));
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 2;
        gridBagConstraints.gridy = 1;
        pIgic.add(txtCuota3, gridBagConstraints);

        txtCuota7.setEditable(false);
        txtCuota7.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        txtCuota7.setHorizontalAlignment(javax.swing.JTextField.CENTER);
        txtCuota7.setText("0,0000€");
        txtCuota7.setBorder(null);
        txtCuota7.setMinimumSize(new java.awt.Dimension(110, 20));
        txtCuota7.setPreferredSize(new java.awt.Dimension(110, 20));
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 2;
        gridBagConstraints.gridy = 2;
        pIgic.add(txtCuota7, gridBagConstraints);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 4;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST;
        gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 2);
        getContentPane().add(pIgic, gridBagConstraints);

        pBotones.setMinimumSize(new java.awt.Dimension(170, 80));
        pBotones.setPreferredSize(new java.awt.Dimension(170, 80));

        bGuardar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/guardar.png"))); // NOI18N
        bGuardar.setMaximumSize(new java.awt.Dimension(71, 71));
        bGuardar.setMinimumSize(new java.awt.Dimension(71, 71));
        bGuardar.setPreferredSize(new java.awt.Dimension(71, 71));
        bGuardar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bGuardarActionPerformed(evt);
            }
        });
        pBotones.add(bGuardar);

        bBorrar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/cancelar.png"))); // NOI18N
        bBorrar.setMaximumSize(new java.awt.Dimension(71, 71));
        bBorrar.setMinimumSize(new java.awt.Dimension(71, 71));
        bBorrar.setPreferredSize(new java.awt.Dimension(71, 71));
        bBorrar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bBorrarActionPerformed(evt);
            }
        });
        pBotones.add(bBorrar);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 4;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
        getContentPane().add(pBotones, gridBagConstraints);

        pFinal.setMinimumSize(new java.awt.Dimension(500, 30));
        pFinal.setPreferredSize(new java.awt.Dimension(500, 30));

        jLabel16.setText("Comentario");
        pFinal.add(jLabel16);

        txtComentario.setHorizontalAlignment(javax.swing.JTextField.CENTER);
        txtComentario.setMinimumSize(new java.awt.Dimension(420, 20));
        txtComentario.setPreferredSize(new java.awt.Dimension(420, 20));
        txtComentario.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                txtComentarioMouseClicked(evt);
            }
        });
        pFinal.add(txtComentario);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 5;
        gridBagConstraints.gridwidth = 2;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
        gridBagConstraints.insets = new java.awt.Insets(0, 0, 20, 0);
        getContentPane().add(pFinal, gridBagConstraints);

        pPrecio.setMinimumSize(new java.awt.Dimension(295, 90));
        pPrecio.setName(""); // NOI18N
        pPrecio.setOpaque(false);
        pPrecio.setPreferredSize(new java.awt.Dimension(295, 90));
        pPrecio.setLayout(new java.awt.GridBagLayout());

        jLabel14.setText("Descuento");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridy = 1;
        gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 2);
        pPrecio.add(jLabel14, gridBagConstraints);

        txtDescuentoPie.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
        txtDescuentoPie.setHorizontalAlignment(javax.swing.JTextField.CENTER);
        txtDescuentoPie.setText("0%");
        txtDescuentoPie.setMinimumSize(new java.awt.Dimension(60, 28));
        txtDescuentoPie.setPreferredSize(new java.awt.Dimension(60, 28));
        txtDescuentoPie.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                txtDescuentoPieMouseClicked(evt);
            }
        });
        txtDescuentoPie.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                txtDescuentoPieKeyReleased(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridy = 1;
        pPrecio.add(txtDescuentoPie, gridBagConstraints);

        jLabel17.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel17.setText("Subtotal");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 2;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST;
        gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 2);
        pPrecio.add(jLabel17, gridBagConstraints);

        txtPrecioFinal.setEditable(false);
        txtPrecioFinal.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
        txtPrecioFinal.setHorizontalAlignment(javax.swing.JTextField.CENTER);
        txtPrecioFinal.setText("0,0000€");
        txtPrecioFinal.setBorder(null);
        txtPrecioFinal.setMinimumSize(new java.awt.Dimension(120, 30));
        txtPrecioFinal.setPreferredSize(new java.awt.Dimension(120, 30));
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 3;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST;
        pPrecio.add(txtPrecioFinal, gridBagConstraints);

        jLabel18.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel18.setText("Total IGIC");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 2;
        gridBagConstraints.gridy = 2;
        gridBagConstraints.insets = new java.awt.Insets(0, 3, 0, 0);
        pPrecio.add(jLabel18, gridBagConstraints);

        txtTotalIGIC.setEditable(false);
        txtTotalIGIC.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
        txtTotalIGIC.setHorizontalAlignment(javax.swing.JTextField.CENTER);
        txtTotalIGIC.setText("0,0000€");
        txtTotalIGIC.setBorder(null);
        txtTotalIGIC.setMinimumSize(new java.awt.Dimension(120, 30));
        txtTotalIGIC.setPreferredSize(new java.awt.Dimension(120, 30));
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 3;
        gridBagConstraints.gridy = 2;
        pPrecio.add(txtTotalIGIC, gridBagConstraints);

        jLabel20.setText("Gastos");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 2;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 2);
        pPrecio.add(jLabel20, gridBagConstraints);

        txtGastos.setEditable(false);
        txtGastos.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
        txtGastos.setHorizontalAlignment(javax.swing.JTextField.CENTER);
        txtGastos.setText("0,0000€");
        txtGastos.setBorder(null);
        txtGastos.setMinimumSize(new java.awt.Dimension(120, 30));
        txtGastos.setPreferredSize(new java.awt.Dimension(120, 30));
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 3;
        gridBagConstraints.gridy = 1;
        pPrecio.add(txtGastos, gridBagConstraints);

        txtSobreCargo.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        txtSobreCargo.setHorizontalAlignment(javax.swing.JTextField.CENTER);
        txtSobreCargo.setToolTipText("0.000");
        txtSobreCargo.setMinimumSize(new java.awt.Dimension(60, 28));
        txtSobreCargo.setPreferredSize(new java.awt.Dimension(60, 28));
        txtSobreCargo.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                txtSobreCargoMouseClicked(evt);
            }
        });
        txtSobreCargo.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                txtSobreCargoKeyReleased(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 0;
        pPrecio.add(txtSobreCargo, gridBagConstraints);

        jLabel1.setText("<html><p align=center> % <br> sobrecargo</p>");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 0;
        pPrecio.add(jLabel1, gridBagConstraints);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 4;
        gridBagConstraints.gridwidth = 2;
        gridBagConstraints.gridheight = 2;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST;
        gridBagConstraints.insets = new java.awt.Insets(0, 20, 0, 20);
        getContentPane().add(pPrecio, gridBagConstraints);

        lblError.setFont(new java.awt.Font("Tahoma", 0, 36)); // NOI18N
        lblError.setForeground(new java.awt.Color(255, 0, 0));
        lblError.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        lblError.setText("<html><p align=center> ¡¡¡¡Error!!!!<br> Ticket no Existe</p>");
        lblError.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED));
        lblError.setMinimumSize(new java.awt.Dimension(300, 100));
        lblError.setOpaque(true);
        lblError.setPreferredSize(new java.awt.Dimension(300, 100));
        lblError.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                lblErrorMouseClicked(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 3;
        gridBagConstraints.gridwidth = 3;
        getContentPane().add(lblError, gridBagConstraints);

        jScrollPane1.setMinimumSize(new java.awt.Dimension(300, 150));
        jScrollPane1.setPreferredSize(new java.awt.Dimension(300, 150));

        tabla.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null, null, null, null, null}
            },
            new String [] {
                "Codigo", "Detalle", "Cantidad", "Precio", "Dto%", "Total", "I.G.I.C.", "Costo"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.String.class, java.lang.String.class, java.lang.Float.class, java.lang.Float.class, java.lang.String.class, java.lang.Float.class, java.lang.Float.class, java.lang.Float.class
            };
            boolean[] canEdit = new boolean [] {
                true, true, true, true, true, false, true, true
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        tabla.setToolTipText("<html> boton dcho: abre el articulo<br> f5: borra linea");
        tabla.getTableHeader().setReorderingAllowed(false);
        tabla.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tablaMouseClicked(evt);
            }
        });
        tabla.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                tablaKeyPressed(evt);
            }
            public void keyReleased(java.awt.event.KeyEvent evt) {
                tablaKeyReleased(evt);
            }
        });
        jScrollPane1.setViewportView(tabla);
        if (tabla.getColumnModel().getColumnCount() > 0) {
            tabla.getColumnModel().getColumn(0).setResizable(false);
            tabla.getColumnModel().getColumn(0).setPreferredWidth(100);
            tabla.getColumnModel().getColumn(1).setResizable(false);
            tabla.getColumnModel().getColumn(1).setPreferredWidth(300);
            tabla.getColumnModel().getColumn(2).setResizable(false);
            tabla.getColumnModel().getColumn(3).setResizable(false);
            tabla.getColumnModel().getColumn(4).setResizable(false);
            tabla.getColumnModel().getColumn(4).setPreferredWidth(70);
            tabla.getColumnModel().getColumn(5).setResizable(false);
            tabla.getColumnModel().getColumn(6).setResizable(false);
            tabla.getColumnModel().getColumn(6).setPreferredWidth(60);
            tabla.getColumnModel().getColumn(7).setResizable(false);
        }

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 3;
        gridBagConstraints.gridwidth = 2;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.weighty = 1.0;
        gridBagConstraints.insets = new java.awt.Insets(0, 20, 5, 20);
        getContentPane().add(jScrollPane1, gridBagConstraints);

        pack();
    }// </editor-fold>//GEN-END:initComponents

        
    private void txtCodProveKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtCodProveKeyPressed
        switch (evt.getKeyCode()) {
        case 113:       //f2
            FProveedores c = new FProveedores(this, Util.FCOMPRAS);
            this.getParent().add(c);
            Principal.centrarFrame(c);
            c.show();
            break;
        case 10:        // Enter 
            getProveedor(txtCodProve.getText()); 
            break;
        }            
    }//GEN-LAST:event_txtCodProveKeyPressed

    private void bGuardarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bGuardarActionPerformed
        if (tabla.getRowCount() > 0) {
            if (comprobarCampos ()) {
                int op = JOptionPane.showOptionDialog(this, "Seleccione opcion", "¿Que quiere hacer?", 
                                 JOptionPane.YES_NO_OPTION,JOptionPane.QUESTION_MESSAGE, null,
                                 new Object[] { "Imprimir", "No Imprimir" }, 
                                 "Imprimir"); 
                guardar();
                if (op==0) {
                    DatosToImprimir d = new DatosToImprimir();
                    d.setTabla(tabla);
                    d.setFecha(new Fecha().getFecha());
                    d.setNumTicket(txtId.getText());
                    d.setTipoTicket(cbTipoTicket.getSelectedItem().toString());
                    ImpCompra.imprime(d);
                }
                resetFTPV();
                abrirNuevosArticulos();
            }
        }
    }//GEN-LAST:event_bGuardarActionPerformed

    private void bCargarFacturaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bCargarFacturaActionPerformed
        txtId.setEditable(!txtId.isEditable());
        if (txtId.isEditable()) {
           txtId.setBackground(Color.white);
           txtId.requestFocus();
           txtId.selectAll();
        }
        else
            txtId.setBackground(Util.getColorTicket(cbTipoTicket.getSelectedItem().toString()));
    }//GEN-LAST:event_bCargarFacturaActionPerformed

    private void txtIdMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_txtIdMouseClicked
        if(txtId.isEditable())
            txtId.selectAll();
    }//GEN-LAST:event_txtIdMouseClicked

    private void txtIdKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtIdKeyReleased
        if (evt.getKeyCode() == 10) {
            if (!guardar) {
                Util.restaurarStock(Integer.parseInt(txtId.getText()), true);
            }
            int id = Integer.parseInt(txtId.getText());
            resetFTPV();
            cargar(id);
            tabla.requestFocus();
        } 
    }//GEN-LAST:event_txtIdKeyReleased

    private void txtCodProveMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_txtCodProveMouseClicked
        txtCodProve.selectAll();
    }//GEN-LAST:event_txtCodProveMouseClicked

    private void bBorrarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bBorrarActionPerformed
        // al cargar restauro el stock que habia en factura con lo si cancelo tengo que volver a guardarlo
        if (!guardar) {
            boolean resto = true;
            if (cbTipoTicket.getSelectedIndex()==2) resto = false;  //abono
            Util.restaurarStock(Integer.parseInt(txtId.getText()), resto);
            guardar = true;
        }
        resetFTPV();
        aActualizar.clear();
    }//GEN-LAST:event_bBorrarActionPerformed

    private void formInternalFrameClosed(javax.swing.event.InternalFrameEvent evt) {//GEN-FIRST:event_formInternalFrameClosed
        if (!guardar) {
            boolean resto = true;
            if (cbTipoTicket.getSelectedIndex()==2) resto = false;  //abono
            Util.restaurarStock(Integer.parseInt(txtId.getText()), resto);
        }
        ConsultaBD.cursorNormal(this);
    }//GEN-LAST:event_formInternalFrameClosed

    private void txtComentarioMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_txtComentarioMouseClicked
        txtComentario.selectAll();
    }//GEN-LAST:event_txtComentarioMouseClicked

    private void txtDescuentoPieMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_txtDescuentoPieMouseClicked
        txtDescuentoPie.selectAll();
    }//GEN-LAST:event_txtDescuentoPieMouseClicked

    private void txtDescuentoPieKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtDescuentoPieKeyReleased
        if (evt.getKeyCode() == 10) {
            descPie = Float.parseFloat(txtDescuentoPie.getText().toString()) / 100;
            txtDescuentoPie.setText(txtDescuentoPie.getText() + "%");
            recalcularIgic();
        } 
    }//GEN-LAST:event_txtDescuentoPieKeyReleased

    private void tablaMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tablaMouseClicked
        int fila = tabla.rowAtPoint(evt.getPoint());
        int colum = tabla.columnAtPoint(evt.getPoint());
        if ((fila > -1) && (colum > -1)) {
            setVarFila(fila);
            filaEdit = fila;
            columEdit = colum;
        }
        if (evt.isMetaDown()) {
            String codigo = ""+tabla.getValueAt(fila, 0);
            if (!codigo.equals("null") &&(codigo.length() < 13) && !codigo.equals("0"))
                if (colum==2) 
                    abrirStock(codigo);
                else
                    abrirArticulo(codigo);
        }
    }//GEN-LAST:event_tablaMouseClicked

    private void tablaKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_tablaKeyPressed
        if (evt.getKeyCode() == 10) {
            filaEdit = tabla.getSelectedRow();
            columEdit = tabla.getSelectedColumn();
        }
        if ((evt.getKeyCode() == 113) && (tabla.getSelectedColumn()==0)){   //f2
            filaEdit = tabla.getSelectedRow();
            columEdit = tabla.getSelectedColumn();
            evt.consume();
            abrirBusquedaArticulo(null);
        }
        
//        if ((evt.getKeyCode() == 8) && (tabla.getSelectedColumn()==0)) {    // borro el codigo introducido por error
//            if (tabla.getValueAt(tabla.getSelectedRow(), 0) != null) {
//                String codigo = tabla.getValueAt(tabla.getSelectedRow(), 0).toString();
//                aActualizar.remove(codigo);
//                creados.remove(codigo);
//            }
//        }
    }//GEN-LAST:event_tablaKeyPressed

    private void tablaKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_tablaKeyReleased
        int fila = tabla.getSelectedRow();
        int columna = tabla.getSelectedColumn();
        switch (evt.getKeyCode()) {
            case 37:
            case 38:
            case 39:
            case 40:
                if (fila != filaEdit) {
                    setVarFila(fila);
                    filaEdit = fila;
                }
                tabla.editCellAt(fila, columna);
                tabla.changeSelection(fila, columna, false, false);
                break;
            case 112:    //f1   
            case 116:    //f5
                if (fila > -1) {
                    tabla.getCellEditor().cancelCellEditing();
                    setVarFila(fila);
                    aActualizar.remove(memoriaId);
                    tratarIgic(igic, true);         //resto el igic
                    cantidad = -cantidad;
                    calcularLinea();                // le resto lo que habia en la linea eliminada al total
                    setPrecioFinal();               // le sumo el igic 
                    resetValores();
                    ((DefaultTableModel)tabla.getModel()).removeRow(tabla.getSelectedRow());
                    if ((tabla.getRowCount() == 0) || (fila > tabla.getRowCount()-1))
                        ((DefaultTableModel)tabla.getModel()).addRow(new Object[] {null,null,null,null,null,null,null}); 
                }
                break;
            case 10:
                // movimiento del cursor en la tabla cuando pulsamos enter
                int i = 1;
                if (columEdit == 4) i = 2;
                if (columEdit < 7) {
                    tabla.editCellAt(filaEdit, columEdit+i);
                    tabla.changeSelection(filaEdit, columEdit+i, false, false);
                }
                switch(columEdit) {
                    case 2:     //cantidad
                    case 3:     //precio
                        if (tabla.getValueAt(filaEdit, columEdit) == null || tabla.getValueAt(filaEdit, columEdit).toString().isEmpty())
                            tabla.setValueAt(0,filaEdit,columEdit);
                        break;
                    case 4:     //descuento
                        if (tabla.getValueAt(filaEdit, columEdit) == null || tabla.getValueAt(filaEdit, columEdit).toString().isEmpty())
                            tabla.setValueAt("0",filaEdit,columEdit);
                        break;
                    case 6:     //igic
                        if (tabla.getValueAt(filaEdit, columEdit) == null || tabla.getValueAt(filaEdit, columEdit).toString().isEmpty())
                            tabla.setValueAt(0,filaEdit,columEdit);
                        if (!evt.isConsumed()) evt.consume();
                        if (filaEdit == tabla.getRowCount()-1){
                            ((DefaultTableModel)tabla.getModel()).addRow(new Object[] {null,null,null,null,null,null,null}); 
                            tabla.scrollRectToVisible(tabla.getCellRect(tabla.getRowCount()-1, 0, true));
                        }
                        tabla.editingCanceled(null);
                        tabla.changeSelection(filaEdit+1, 0, false, false);
                        resetValores();
                        break;
                    case 7: 
                        tabla.editCellAt(filaEdit+1, 0);
                        tabla.changeSelection(filaEdit+1, 0, false, false);                        
                        resetValores();
                    break;
                }
                         
            break;
        }
    }//GEN-LAST:event_tablaKeyReleased

    private void txtFechaFacMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_txtFechaFacMouseClicked
        txtFechaFac.selectAll();
    }//GEN-LAST:event_txtFechaFacMouseClicked

    private void txtNumFacMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_txtNumFacMouseClicked
        txtNumFac.selectAll();
    }//GEN-LAST:event_txtNumFacMouseClicked

    private void txtNumFacKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtNumFacKeyReleased
        if (evt.getKeyCode() == 10) {
            txtFechaFac.requestFocus();
            SePuedeGrabar();
        }
    }//GEN-LAST:event_txtNumFacKeyReleased

    private void txtCodProveKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtCodProveKeyReleased
        if (evt.getKeyCode() == 10) {
            txtNumFac.requestFocus();
        }
    }//GEN-LAST:event_txtCodProveKeyReleased

    private void txtFechaFacKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtFechaFacKeyReleased
        if (evt.getKeyCode() == 10) {
            if(Fecha.formatoCorrecto(txtFechaFac.getText())) {
                if (txtFechaVenc.isEnabled()) { 
                    if (txtCodProve.getText().equals("1") && !txtNumFac.getText().contains("/")) {
                        txtSobreCargo.requestFocus();
                        txtFechaVenc.setText(fechaPagoCoarco());
                        txtPeriodo.setText("1");
                    }
                    else
                        txtFechaVenc.requestFocus();
                    
                }
                else
                    txtSobreCargo.requestFocus();
                SePuedeGrabar();
            } 
            else {
                mostrarMensajeError(5);
                activarBotones(false);
            }
        }
    }//GEN-LAST:event_txtFechaFacKeyReleased

    private void cbTipoTicketItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_cbTipoTicketItemStateChanged
        if (evt.getStateChange() == ItemEvent.SELECTED) {
            if (cbTipoTicket.getSelectedIndex() == 1) {
                cbTipoPago.setSelectedIndex(1);
                activarFechaVenc(false);
            }
            else {
                cbTipoPago.setSelectedIndex(0);
                activarFechaVenc(true);
            }
        }
        cambiarEstadoTicket();
    }//GEN-LAST:event_cbTipoTicketItemStateChanged

    private void txtSobreCargoKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtSobreCargoKeyReleased
        if (evt.getKeyCode() == 10) {
            try {
                sobreCargo =  Float.parseFloat(txtSobreCargo.getText().replace("%", "").replace(",", ".").trim());
                if (tabla.getRowCount() > 0) {
                    totalVenta = 0;
                    suma3 = 0;
                    suma7 = 0;
                    for(int i = 0; (i < tabla.getRowCount()) && (tabla.getValueAt(i, 1)!= null); i++) {
                        setVarFila(i);
                        calcularLinea();
                        tratarIgic(igic, false);
                        //tabla.setValueAt(total, i, 5);
                        tabla.setValueAt(calcularCosto(), i, 7);
                    }
                }
                txtSobreCargo.setText(sobreCargo+"%");
                txtGastos.setText(Util.getFormatPrecio(totalVenta * (sobreCargo/100),4));
                tabla.requestFocus();
                tabla.changeSelection(0, 0, false, false);
                SePuedeGrabar();
            } catch (Exception e) {
                ;
            }
        }
    }//GEN-LAST:event_txtSobreCargoKeyReleased

    private void txtSobreCargoMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_txtSobreCargoMouseClicked
        txtSobreCargo.selectAll();
    }//GEN-LAST:event_txtSobreCargoMouseClicked

    private void txt3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txt3ActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_txt3ActionPerformed

    private void bXMLActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bXMLActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_bXMLActionPerformed

    private void txtFechaPagoMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_txtFechaPagoMouseClicked
        txtFechaPago.selectAll();
    }//GEN-LAST:event_txtFechaPagoMouseClicked

    private void cbTipoPagoItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_cbTipoPagoItemStateChanged
        if (evt.getStateChange() == ItemEvent.SELECTED) {
            if (cbTipoPago.getSelectedIndex() == 0) {
                activarFechaPago(true);
            }
            else {
                activarFechaPago(false);
                txtFechaPago.setText("");
            }
        }
    }//GEN-LAST:event_cbTipoPagoItemStateChanged

    private void txtFechaVencMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_txtFechaVencMouseClicked
        txtFechaVenc.selectAll();
    }//GEN-LAST:event_txtFechaVencMouseClicked

    private void txtFechaVencKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtFechaVencKeyReleased
        if (evt.getKeyCode() == 10) {
            if (txtPeriodo.getText().isEmpty())
                txtPeriodo.setText("1");
            txtPeriodo.requestFocus();
        }
    }//GEN-LAST:event_txtFechaVencKeyReleased

    private void txtPeriodoMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_txtPeriodoMouseClicked
        txtPeriodo.selectAll();
    }//GEN-LAST:event_txtPeriodoMouseClicked

    private void lblErrorMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_lblErrorMouseClicked
        mostrarMensajeError(false);
    }//GEN-LAST:event_lblErrorMouseClicked

    private void txtPeriodoKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtPeriodoKeyReleased
        if (evt.getKeyCode() == 10) {
            if (txtFechaPago.isEnabled()) 
                txtFechaPago.requestFocus();
            else
                txtSobreCargo.requestFocus();
            SePuedeGrabar();
        }
    }//GEN-LAST:event_txtPeriodoKeyReleased

    private void lblF3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_lblF3ActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_lblF3ActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton bBorrar;
    private javax.swing.JButton bCargarFactura;
    private javax.swing.JButton bGuardar;
    private javax.swing.JButton bXML;
    private javax.swing.JComboBox cbTipoPago;
    private javax.swing.JComboBox cbTipoTicket;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel13;
    private javax.swing.JLabel jLabel14;
    private javax.swing.JLabel jLabel15;
    private javax.swing.JLabel jLabel16;
    private javax.swing.JLabel jLabel17;
    private javax.swing.JLabel jLabel18;
    private javax.swing.JLabel jLabel19;
    private javax.swing.JLabel jLabel20;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JLabel lblError;
    private javax.swing.JTextField lblF3;
    private javax.swing.JLabel lblTime;
    private javax.swing.JPanel pBotones;
    private javax.swing.JPanel pCliente;
    private javax.swing.JPanel pFinal;
    private javax.swing.JPanel pIgic;
    private javax.swing.JPanel pPrecio;
    private javax.swing.JPanel pProductos;
    private javax.swing.JPanel pReloj;
    private javax.swing.JPanel pTipoTicket;
    private javax.swing.JTable tabla;
    private javax.swing.JTextField txt3;
    private javax.swing.JTextField txt7;
    public javax.swing.JTextField txtCodProve;
    private javax.swing.JTextField txtComentario;
    private javax.swing.JTextField txtCuota3;
    private javax.swing.JTextField txtCuota7;
    private javax.swing.JTextField txtDescuentoPie;
    private javax.swing.JLabel txtF3;
    private javax.swing.JTextField txtFechaFac;
    private javax.swing.JTextField txtFechaPago;
    private javax.swing.JTextField txtFechaVenc;
    private javax.swing.JTextField txtGastos;
    private javax.swing.JFormattedTextField txtId;
    private javax.swing.JTextField txtImp3;
    private javax.swing.JTextField txtImp7;
    public javax.swing.JTextField txtNomComercial;
    private javax.swing.JTextField txtNumFac;
    private javax.swing.JTextField txtPeriodo;
    private javax.swing.JTextField txtPrecioDigital;
    private javax.swing.JTextField txtPrecioFinal;
    private javax.swing.JTextField txtSobreCargo;
    private javax.swing.JTextField txtTotalIGIC;
    // End of variables declaration//GEN-END:variables
}
